<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
    <% String path=request.getContextPath(); String basePath=request.getScheme() + "://" + request.getServerName() + ":"
        + request.getServerPort() + path + "/" ; %>
        <!DOCTYPE html>
        <html>

        <head>
            <base href="<%=basePath%>">
            <title>我的中标</title>
            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
            <meta http-equiv="description" content="This is my page">
        </head>
        <style>
            .tdText {
                text-align: right;
                width: 400px;
                height: 20px;
            }
        </style>

        <body>
            <%@ include file="/WEB-INF/jsp/common/headerSupply.jsp" %>
                <%@ include file="/WEB-INF/jsp/common/loadDiv.jsp" %>

                    <script type="text/javascript">
                        $(function () {
                            $('#startTime').datebox('setValue', getBeforeCurrentDate30Days());
                            $('#endTime').datebox('setValue', getNowFormatDate());
                            bingGrid();
                        });

                    </script>

                    <div class="query_criteria" id="query_criteria">
                        <div style="margin: 5px 0px">
                            <%-- 搜索框 --%>
                                <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
                                    name="startTime" id="startTime"
                                    data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                    value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                    class="easyui-datebox" name="endTime" id="endTime"
                                    data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                    style="width: 150px" />
                                <a id="search" style="margin-left: 30px" href="javascript:void(0)"
                                    class="easyui-linkbutton" data-options="iconCls:'icon-search'"
                                    onclick="selectList()">查询</a>
                        </div>
                        <%--我的报价列表DataGrid --%>
                            <table id="dataGridDiv"></table>
                            <%-- 详情弹窗 --%>
                                <div id="supplyOfferWindow" class="easyui-window" closed="true" modal="true"
                                    title="供应商报价" style="width: 900px; height: 400px; padding: 5px 5px">
                                    <form id="supplyOfferForm">
                                        <div class="easyui-tabs" id="tabs" style="width: 875px; height: 350px">
                                            <div title="基本信息">
                                                <table>
                                                    <tr style="margin-bottom: 10px">
                                                        <td colspan="1" class="tdText"><input id="infId" type="hidden"
                                                                class="easyui-validatebox textbox" style="width: 60%">
                                                            <label style="width: 40%; text-align: right;">订单名称：</label>
                                                            <input id="ordName" class="easyui-validatebox textbox"
                                                                style="width: 60%"> <input id="inqId" type="hidden"
                                                                class="easyui-validatebox textbox" style="width: 60%">
                                                        </td>
                                                        <!-- <td colspan="1" class="tdText"><label
                                                                style="width: 40%; text-align: right;">联系人：</label>
                                                            <input id="infContact" class="easyui-validatebox textbox"
                                                                style="width: 60%" data-options="required:true">
                                                        </td>
                                                        <td colspan="1" class="tdText"><label
                                                                style="width: 40%; text-align: right;">联系电话：</label>
                                                            <input id="infContactTel" class="easyui-validatebox textbox"
                                                                style="width: 60%" data-options="required:true">
                                                        </td> -->
                                                        <%--<td colspan="1" class="tdText">
                                                            <label style="width:40%;text-align:right;">报价开始时间：</label>
                                                            <input id="inqStartTime" class="easyui-datebox"
                                                                style="width: 60%">
                                                            </td>
                                                            <td colspan="1" class="tdText">
                                                                <label
                                                                    style="width:40%;text-align:right;">报价结束时间：</label>
                                                                <input id="inqEndTime" class="easyui-datebox"
                                                                    style="width: 60%">
                                                            </td>--%>
                                                            <td colspan="1" class="tdText"><label
                                                                    style="width: 40%; text-align: right;">提交时间：</label>
                                                                <input id="createTime" class="easyui-datetimebox"
                                                                    data-options="disabled:true" style="width: 60%">
                                                            </td>
                                                    </tr>
                                                    <%-- <tr style="margin-bottom: 10px">

                                                        <td colspan="1" class="tdText"><label
                                                                style="width: 40%; text-align: right;">备注：</label>
                                                            <input id="remark" class="easyui-textbox"
                                                                data-options="multiline:true"
                                                                style="width: 60%; height: 100px">
                                                        </td>
                                                        <td colspan="1" class="tdText">
                                                            <label style="width:40%;text-align:right;">创建时间：</label>
                                                            <input id="createTime" class="easyui-datebox"
                                                                style="width: 60%">
                                                        </td>
                                                        <td colspan="1" class="tdText">
                                                            <label style="width:40%;text-align:right;">创建人：</label>
                                                            <input id="createName" class="easyui-validatebox textbox"
                                                                style="width: 60%">
                                                        </td>
                                                        </tr>--%>
                                                        <%-- <tr style="margin-bottom: 10px">

                                                            <td colspan="1" class="tdText">
                                                                <label style="width:40%;text-align:right;">更新人：</label>
                                                                <input id="updateName"
                                                                    class="easyui-validatebox textbox"
                                                                    style="width: 60%">
                                                            </td>
                                                            <td colspan="1" class="tdText">
                                                                <label style="width:40%;text-align:right;">更新时间：</label>
                                                                <input id="updateTime" class="easyui-datebox"
                                                                    style="width: 60%">
                                                            </td>
                                                            </tr>--%>
                                                </table>

                                            </div>
                                            <div title="物资报价明细">
                                                <table id="supplMMOfferList"></table>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                    </div>


        </body>
        <script type="text/javascript">
            var editIndex = undefined;

            // 行编辑结束
            function endEditing() {
                if (editIndex == undefined) {
                    return true
                }
                if ($('#supplMMOfferList').datagrid('validateRow', editIndex)) {
                    $('#supplMMOfferList').datagrid('endEdit', editIndex);
                    editIndex = undefined;
                    return true;
                } else {
                    return false;
                }
            }

            // 待报价物资明细列表的列
            const notOfferedColmus = [[
                {
                    field: 'infId',
                    title: '供应商id',
                    hidden: true,
                    formatter: function (val, rec, index) {
                        return val ? val : '';
                    }
                },
                {
                    field: 'inqId',
                    title: '询价id',
                    hidden: true,
                    formatter: function (val, rec, index) {
                        return val ? val : '';
                    }
                },
                {
                    field: 'mmId',
                    title: '物资id',
                    hidden: true,
                    formatter: function (val, rec, index) {
                        return val ? val : '';
                    }
                },
                {
                    field: 'planId',
                    title: '采购计划_id',
                    hidden: true,
                    width: 100,
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'gramId',
                    title: '采购方案ID',
                    hidden: true,
                    width: 100,
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'mmUnit',
                    title: '计量单位',
                    sortable: true,
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'gramPurNum',
                    title: '招标数量',
                    sortable: true,
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'inqOfrNum',
                    title: '报价数量',
                    sortable: true,
                    width: 100,
                    editor: { type: 'numberbox', options: { precision: 0 } },
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'dealNum',
                    title: '中标数量',
                    sortable: true,
                    width: 100,
                    editor: { type: 'numberbox', options: { precision: 0 } },
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'dealUnitPrice',
                    title: '单价',
                    sortable: true,
                    width: 100,
                    editor: { type: 'numberbox', options: { precision: 0 } },
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                {
                    field: 'dealTotalPrice',
                    title: '中标金额',
                    sortable: true,
                    width: 100,
                    // editor: {type: 'numberbox', options: {precision: 0}},
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                //         {
                //             field: 'inqTaxRate',
                //             title: '税率',
                //             //  editor: {type: 'numberbox', options: {precision: 0}},
                //             sortable: true,
                //             formatter: function (val, rec) {
                //                 return unescape(val ? val : '')
                //             }
                //         },
                {
                    field: 'inqTaxNum',
                    title: '税码',
                    width: 100,
                    editor: {
                        type: 'combobox',
                        options: {
                            url: 'sysDict/queryItemByTypeName?dicName=税码',
                            method: 'get',
                            valueField: "dicValue",
                            textField: "dicName",
                            editable: false,
                            required: true,
                            onSelect: function (record) {
                            }
                        }
                    },
                    sortable: true,
                    formatter: function (val, rec) {
                        return rec.inqTaxRate
                    }
                },
                {
                    field: 'inqDeliverDate',
                    title: '交货日期',
                    sortable: true,
                    editor: { type: 'datebox' },
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                /*  {
                      field: 'inqOfrExcludePrice',
                      title: '不含税价格',
                      editor: {type: 'numberbox', options: {precision: 0}},
                      sortable: true,
                      formatter: function (val, rec) {
                          return unescape(val ? val : '')
                      }
                  },*/

                {
                    field: 'createTime',
                    title: '创建时间',
                    sortable: true,
                    formatter: function (val, rec) {
                        return unescape(val ? val : '')
                    }
                },
                /* {
                     field: 'updateTime',
                     title: '更新时间',
                     sortable: true,
                     formatter: function (val, rec) {
                         return unescape(val ? val : '')
                     }
                 }*/
                /* {
                     field: 'status',
                     title: '状态',
                     sortable: true,
                     formatter: function (val, rec) {
                         let status = val ? val : '';
                         return unescape(status == '0' ? '待提交' : '已提交');
                     }
                 }*/
            ]];

            /**
             * 编辑报价信息
             */
            function editRow() {
                let offerRow = $('#dataGridDiv').datagrid('getSelected');
                if (!offerRow) {
                    $.messager.alert('提示', '请选择一条数据');
                    return
                }
                // if (+offerRow.status == 1) {
                //     $.messager.alert('提示', '该报价已提交，不允许再次修改')
                //     return
                // }

                setOfferDetailWindowValue(offerRow, 'edit');
            }

            /**
             * 查看报价详情
             */
            function viewDetails() {
                let offerRow = $('#dataGridDiv').datagrid('getSelected');
                if (!offerRow) {
                    $.messager.alert('提示', '请选择一条数据');
                    return
                }


                setOfferDetailWindowValue(offerRow)
            }

            /**
             * 报价详情(编辑)窗口赋值
             */

            function setOfferDetailWindowValue(item, action) {
                if (+item.status != 1) {

                }
                $.ajax({
                    type: 'get',
                    dataType: 'json',
                    url: 'supply/offer/selectBidMmList?resId=' + item.resId + '&infId=' + item.infId,
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                        } else {
                            $('#infId').val(item.infId)
                            $('#ordName').val(item.ordName);
                            $('#infContact').val(item.infContact);
                            $('#infContactTel').val(item.infContactTel);
                            $('#ordName').textbox({ disabled: true });
                            $('#inqId').val(item.inqId);
                            //  $('#inqOfrIncludePrice').numberbox('setValue', item.inqOfrIncludePrice);
                            // $('#inqOfrTime').datetimebox('setValue', item.inqOfrTime);
                            $('#inqStartTime').datebox('setValue', item.inqStartTime);
                            $('#inqEndTime').datebox('setValue', item.inqEndTime);
                            $('#remark').val(item.remark);
                            $('#createTime').datebox('setValue', item.createTime);
                            $('#createName').val(item.createName);
                            $('#gramDeptCode').val(item.gramDeptCode);
                            $('#gramDeptName').val(item.gramDeptName);
                            $('#gramGetDeptCode').val(item.gramGetDeptCode);
                            $('#gramIsUrgent').val(item.gramIsUrgent);
                            $('#gramFlowType').val(item.gramFlowType);
                            $('#createTime').val(item.createTime);
                            $('#createName').val(item.createName);
                            //    $('#updateName').val(item.updateName);
                            //   $('#updateTime').datebox('setValue', item.updateTime);
                            // 构建物资报价明细的dataGrid
                            const purchaseSupplyOfferMms = data.rows
                            setMmsDatagird(purchaseSupplyOfferMms);

                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
                $('#supplyOfferWindow').window('open');
            }

            /**
             *
             */
            function openOfferDetail(index) {
                let dg = $('#dataGridDiv')
                const rows = dg.datagrid('getRows')
                let row = rows[index]
                setOfferDetailWindowValue(row)
            }

            // 保存/提交
            function saveSupplyOfferMM(action) {
                if (!$('#supplyOfferForm').form('validate')) {
                    alert('请先完成数据录入!');
                    return;
                }
                let offerStatus = '0';
                if (action == 'submit') {
                    offerStatus = "1";
                }
                // 1.首先关闭编辑器
                $('#supplMMOfferList').datagrid('endEdit', editIndex);
                editIndex = undefined;
                // 2.获取物资明细
                const supplMMOfferList = $('#supplMMOfferList').datagrid('getRows');
                // 取得报价总数量与合计价格
                let inqOfrNum = 0
                let inqOfrTotalPrice = 0
                if (supplMMOfferList != null && supplMMOfferList.length > 0) {
                    for (let i in supplMMOfferList) {
                        // 报价数量
                        let oferNum = supplMMOfferList[i].inqOfrNum ? Number(supplMMOfferList[i].inqOfrNum) : 0
                        // 报价单价
                        let oferPrice = supplMMOfferList[i].inqOfrUnitPrice ? Number(supplMMOfferList[i].inqOfrUnitPrice) : 0
                        // 报价总数量
                        inqOfrNum += oferNum
                        // 物资列的含税价格重新赋值
                        supplMMOfferList[i].inqOfrTotalPrice = oferPrice * oferNum
                        // 合计价格
                        inqOfrTotalPrice += oferPrice * oferNum
                    }
                }
                // 调用后台接口保存
                let PurchaseSupplyOfferVO = {
                    inqId: $('#inqId').val(),
                    infContactTel: $('#infContactTel').val(),
                    infContact: $('#infContact').val(),
                    status: offerStatus,
                    // 第一次报价总额
                    inqOfrTotalPrice: inqOfrTotalPrice,
                    // 第一次报价总数量
                    inqOfrNum: inqOfrNum,
                    purchaseSupplyOfferMms: supplMMOfferList
                }
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: 'supply/offer/saveOfferMm',
                    data: JSON.stringify(PurchaseSupplyOfferVO),
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                        } else {
                            $.messager.alert('消息', data.msg);
                            let dg = $('#dataGridDiv');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                            $('#supplyOfferWindow').window('close');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            $('#supplyOfferWindow').window({
                onBeforeClose: function () {
                    // onClose: function () {
                    $('#supplMMOfferList').datagrid('endEdit', editIndex);
                    editIndex = undefined;
                }
            })

            // 构建物资明细dataGrid
            function setMmsDatagird(data) {
                let supplMMOfferList = $('#supplMMOfferList')
                supplMMOfferList.datagrid({
                    //             fitColumns: true,
                    data: data,
                    iconCls: 'icon-application',
                    clientPaging: false,
                    filterDelay: 0,
                    width: 850,
                    height: 300,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    frozenColumns: [
                        [{
                            field: 'mmCode',
                            title: '物资编码',
                            sortable: true,
                            width: 120,
                            formatter: function (val, rec) {
                                return unescape(val ? val : '')
                            }
                        },
                        {
                            field: 'mmDetail',
                            title: '物资描述',
                            sortable: true,
                            width: 300,
                            formatter: function (val, rec) {
                                return unescape(val ? val : '')
                            }
                        }
                        ]
                    ],
                    columns: notOfferedColmus,
                    // onEndEdit: onEndEdit,
                    // 行单击事件
                    // onClickRow: onClickCell,
                    onLoadSuccess: function () {

                    },
                    toolbar: [{
                        text: '导出',
                        iconCls: 'icon-export',
                        handler: function () {
                            exportMmList();
                        }
                    }
                    ],
                });
                supplMMOfferList.datagrid('enableFilter');
            }


            // 导出采购计划列表
            function exportMmList() {
                let gramMmRows = $('#dataGridDiv').datagrid('getSelected');
                var form = [];
                form.push('resId=' + gramMmRows.resId);
                form.push('infId=' + gramMmRows.infId);
                let url = 'api/supply/offer/exportBidMmList'
                let xhr = new XMLHttpRequest()
                xhr.open('POST', url, true)
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader('token', localStorage.getItem('tokenSupply'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = '报价明细' + new Date().getTime() + '.xlsx'
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    }
                }
                xhr.send(form.join('&'))
            }

            function onClickCell(index, field) {
                if (editIndex != index) {
                    if (endEditing()) {
                        $('#supplMMOfferList').datagrid('selectRow', index)
                            .datagrid('beginEdit', index);
                        var ed = $('#supplMMOfferList').datagrid('getEditor', { index: index, field: field });
                        if (ed) {
                            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                        }
                        editIndex = index;
                    } else {
                        setTimeout(function () {
                            $('#supplMMOfferList').datagrid('selectRow', editIndex);
                        }, 0);
                    }
                }
            }
            function onEndEdit(index, row) {
                var ed = $(this).datagrid('getEditor', {
                    index: index,
                    field: 'inqTaxNum'
                });
                row.inqTaxRate = $(ed.target).combobox('getText');
            }
            /**
             *  按条件查询报价列表
             */

            function selectList() {
                var startTime = $('#startTime').datebox('getValue')
                var endTime = $('#endTime').datebox('getValue')
                // var offerStatus = $('#supplyOfferStatus').combobox('getValue');
                var dg = $('#dataGridDiv');
                dg.datagrid('enableFilter');
                dg.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    // status: offerStatus ? offerStatus : ''
                });
            }


            /**
             * 构建报价列表datagrid
             */

            function bingGrid() {
                let dg = $('#dataGridDiv');
                let startTime = $('#startTime').datebox('getValue') ? $('#startTime').datebox('getValue') : ''
                let endTime = $('#endTime').datebox('getValue') ? $('#endTime').datebox('getValue') : ''
                // let status = $('#supplyOfferStatus').combobox('getValue') ? $('#supplyOfferStatus').combobox('getValue') : ''
                dg.datagrid({
                    title: '中标列表',
                    queryParams: {
                        startTime: startTime,
                        endTime: endTime,
                        // status: status
                    },
                    fitColumns: false,
                    fit: false,
                    url: 'supply/offer/selectBidList',
                    iconCls: 'icon-application',
                    clientPaging: false,
                    remoteFilter: true,
                    filterDelay: 0,
                    width: getWidth(0.98),
                    height: 415,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    pageSize: 10,
                    remoteSort: false,
                    pagination: true,
                    frozenColumns: [[
                        {
                            field: 'infId',
                            title: '供应商id',
                            hidden: true,
                            formatter: function (val, rec, index) {
                                return val ? val : '';
                            }
                        },
                        {
                            field: 'ordCode',
                            title: '订单编号',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return (val ? val : '')
                            }
                        },
                        {
                            field: 'ordName',
                            title: '订单名称',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return '<a href="javascript:void(0)" onclick="openOfferDetail(' + index +
                                    ')">' + (val ? val : '') + '</a>'
                                // return '<a href="javascript:void(0)" onclick="setOfferDetailWindowValue(' + index+')">' + (val ? val : '') + '</a>'
                            }
                        }
                    ]],
                    columns: [[
                        // {
                        //     field: 'inqOfrTime',
                        //     title: '提交时间',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return unescape(val ? val : '')
                        //     }
                        // },
                        {
                            field: 'ordFreight',
                            title: '金额',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val ? val : 0)
                            }
                        },
                        // {
                        //     field: 'infFirstNum',
                        //     title: '合同开始时间',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return unescape(val ? val : 0)
                        //     }
                        // },
                        // {
                        //     field: 'infLastTotalPrice',
                        //     title: '合同结束时间',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return unescape(val ? val : '')
                        //     }
                        // },
                        {
                            field: 'inqContractStart',
                            title: '合同起始日期',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val ? val : '')
                            }
                        },
                        {
                            field: 'inqContractEnd',
                            title: '合同结束日期',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val ? val : '')
                            }
                        },
                        // {
                        //     field: 'infNum',
                        //     title: '中标数量',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return unescape(val ? val : '')
                        //     }
                        // },

                        // {
                        //     field: 'remark',
                        //     title: '备注',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         return unescape(val ? val : '')
                        //     }
                        // },
                        {
                            field: 'createTime',
                            title: '创建时间',
                            sortable: true,
                            formatter: function (val, rec) {
                                return unescape(val ? val : '')
                            }
                        },
                        /* {
                             field: 'updateTime',
                             title: '更新时间',
                             sortable: true,
                             formatter: function (val, rec) {
                                 return unescape(val ? val : '')
                             }
                         },*/
                        // {
                        //     field: 'status',
                        //     title: '状态',
                        //     sortable: true,
                        //     formatter: function (val, rec) {
                        //         let status = val ? val : '';
                        //         return unescape(status == '0' ? '待报价' : '已报价');
                        //     }
                        // }
                    ]],
                    toolbar: [

                        {
                            text: '查看报价',
                            iconCls: 'icon-search',
                            handler: function () {
                                viewDetails();
                            }
                        }
                    ],
                    onLoadSuccess: function () {

                    },
                    onDblClickRow: function (rowIndex, rowData) {
                        editRow();
                    }

                });
                dg.datagrid('enableFilter');
            }


        </script>

        </html>